package com.lxmMq.Listener;

import cn.hutool.json.JSONUtil;
import com.lxmMq.common.BlogConstants;
import com.lxmMq.entity.Blog;
import com.lxmMq.mapper.BlogDao;
import com.rabbitmq.client.Channel;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class DelayBlogPublishListener {
    @Resource
    private BlogDao blogDao;

    @RabbitListener(queues = BlogConstants.BLOG_DEAD_QUEUE_DEAD_NAME, ackMode = "MANUAL")
    public void delayBlogPublish(@NotNull Message msg, @NotNull Channel channel) {
        long deliveryTag = msg.getMessageProperties().getDeliveryTag();
        try {
            String body = new String(msg.getBody());
            Blog blog = JSONUtil.toBean(body, Blog.class);
            blogDao.insert(blog);
            channel.basicAck(deliveryTag, true);
            System.out.println("博客延迟发布成功");
        } catch (Exception e) {
            System.out.println("出现异常，消息回退");
            try {
                channel.basicNack(deliveryTag, true, true);
            } catch (IOException ex) {
                System.out.println("消息回退失败");
            }
        }
    }
}
